package cn.anecansaitin.whimsy.common.network;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.test.explayer.GeoPlayer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import software.bernie.geckolib.util.ClientUtils;

/**
 * 玩家模型动画触发包
 */
public record ReplacedPlayerAnimTriggerPack(int playerId, String controllerName, String animName) implements CustomPacketPayload {
    public static final ResourceLocation ID = Whimsy.resource("replaced_player_anim_trigger_packet");
    public static final ClientHandler HANDLER = new ClientHandler();

    public ReplacedPlayerAnimTriggerPack(FriendlyByteBuf buf) {
        this(buf.readVarInt(), buf.readUtf(), buf.readUtf());
    }

    @Override
    public void write(FriendlyByteBuf buf) {
        buf.writeVarInt(playerId);
        buf.writeUtf(this.controllerName == null ? "" : this.controllerName);
        buf.writeUtf(this.animName);
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    public static class ClientHandler {
        private ClientHandler() {}

        public void handle(ReplacedPlayerAnimTriggerPack data, PlayPayloadContext context) {
            context.workHandler().submitAsync(() -> {
                Entity entity = ClientUtils.getLevel().getEntity(data.playerId);

                if (!(entity instanceof Player player)) {
                    return;
                }

                GeoPlayer.INSTANCE.triggerAnim(player, data.controllerName, data.animName);
            });
        }
    }
}
